package jp.co.kayo.gae.takidashibot.service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Level;

import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;

import jp.co.kayo.gae.takidashibot.meta.TakidasiMeta;
import jp.co.kayo.gae.takidashibot.meta.TakidasiSumMeta;
import jp.co.kayo.gae.takidashibot.model.Takidasi;
import jp.co.kayo.gae.takidashibot.model.TakidasiSum;
import jp.co.kayo.gae.takidashibot.utils.TwitterClient;
import twitter4j.StatusUpdate;
import twitter4j.TwitterException;


public class ShuukeiService extends TwitterSerivce {
    
    public void morning() throws TwitterException{
        //集計した日
        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
        
        //集計処理、一日一回
        StringBuilder buf = new StringBuilder();
        buf.append("おはようございますっ、今日も元気にいきましょう！\n");
        buf.append("登録されている炊き出し件数\n");
        
        TakidasiMeta tm = TakidasiMeta.get();
        try {
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            List<Takidasi> list = Datastore.query(tm).asList();
            for(Takidasi t : list){
                if(t.getTag()!=null && t.getTag().length() > 0){
                    Integer count = map.get(t.getTag());
                    if(count == null){
                        map.put(t.getTag(), 1);
                    }
                    else{
                        map.put(t.getTag(), count+1);
                    }
                }
            }
            
            //集計した日付
            for(Map.Entry<String, Integer> ent : map.entrySet()){
                buf.append(ent.getKey()).append(" ").append(ent.getValue()).append("件 ");
                
                Transaction t = Datastore.beginTransaction();
                TakidasiSum tsm = new TakidasiSum();
                Key wk = KeyFactory.createKey(TakidasiSum.class.getSimpleName(), ent.getKey()+now.getTime());
                tsm.setKey(wk);
                tsm.setSmdt(now.getTime());
                tsm.setTag(ent.getKey());
                tsm.setCount(ent.getValue());
                Datastore.put(tsm);
                t.commit();
            }
            buf.append("#takidashi");
            
            //炊き出したんのメインアカウント
            TwitterClient twitter = getTwitter(-1);
            StatusUpdate state = new StatusUpdate(buf.toString());
            twitter.updateState(state);
            
        } catch (Exception e) {
            log.log(Level.WARNING, "mnt0", e);
        }
        finally{
        }
    }

}
